<?php
namespace App\Common\Lib\Com;

use App\Common as com;
use App\Common\Lib\Com\WeakReferencePool as thisWeakReference;

class WeakReferencePoolOrObj extends com\Lib\LibBase {

	/**
	 * @var \WeakReference[]|object
	 */
	private array $weakReferencePoolsOrObj = [];

	/**
	 * @param string $name
	 * @return bool
	 */
	public function has( string $name ):bool {
		return isset( $this->weakReferencePoolsOrObj[ $name ] );
	}

	/**
	 * @param string $name
	 * @return mixed
	 * @throws
	 */
	public function get( string $name ):mixed {
		if( isset( $this->weakReferencePoolsOrObj[ $name ] ) ){
			if( $this->weakReferencePoolsOrObj[ $name ] instanceof \WeakReference ){
				return $this->weakReferencePoolsOrObj[ $name ]->get();
			}else{
				return $this->weakReferencePoolsOrObj[ $name ];
			}
		}
		//
		throw com\Lib\Err\Exception::makeOfNew( '引用不存在', com\Lib\Err\Code::$sysDataNotExist );
	}

	/**
	 *
	 * @param string $name
	 * @return bool
	 */
	public function rm( string $name ):bool {
		if( $this->has( $name ) ){
			return true;
		}
		//
		unset( $this->weakReferencePoolsOrObj[ $name ] );
		//
		return true;
	}

	public function create( string $name, object $object ):bool {
		if( $this->has( $name ) ){
			throw com\Lib\Err\Exception::makeOfNew( '已存在同名引用或对象', com\Lib\Err\Code::$sysAssertError );
		}
		//
		$this->weakReferencePoolsOrObj[ $name ] = $object;
		//
		return true;
	}

}
